import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2025-06-21
 * Time: 22:53
 */
public class Mergesort {
    public static void mergeSort(int[] arr) {
        mergeFunc(arr,0,arr.length-1);
    }

    public static void mergeFunc(int[] arr,int left,int right) {
        if(left >= right) {
            return;
        }
        int mid = (left+right) / 2;
        mergeFunc(arr,left,mid);
        mergeFunc(arr,mid+1,right);
        merge(arr,left,right,mid);
    }

    public static void merge(int[] arr,int left,int right,int mid) {
        int start1 = left;
        int start2 = mid+1;
        int k = 0;
        int[] tmp = new int[right-left+1];
        while(start1 <= mid && start2 <= right) {
            if(arr[start1] < arr[start2]) {
                tmp[k++] = arr[start1++];
            } else {
                tmp[k++] = arr[start2++];
            }
        }

        while(start1 <= mid) {
            tmp[k++] = arr[start1++];
        }

        while(start2 <= right) {
            tmp[k++] = arr[start2++];
        }

        for(int i = 0; i < k; i++) {
            arr[left+i] = tmp[i];
        }
    }

    public static void main(String[] args) {
        int[] arr = {1,4,2,9,6,7};
        mergeSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
